package com.vma.jifu.service.impl;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.vma.jifu.bizModel.model.*;
import com.vma.jifu.service.UserService;
import com.vma.tools.AppException;
import com.vma.tools.MDA;
import com.vma.tools.StringUtils;
import com.vma.tools.Utils;
import com.vma.tools.wxGZH.WebAccessToken;
import com.vma.tools.wxGZH.WxGzhUtils;
import org.apache.commons.lang.RandomStringUtils;

import java.util.*;

/**
 * Created by chenzui on 2017/6/15.
 */
public class UserServiceImpl implements UserService {

    private static final User dao = new User().dao();

    public User login(String loginAccount, String pwd) {
        User user;
        if(loginAccount.length()==11){
            user = User.dao.findFirst("select * from `user` where phone  = ?",loginAccount);
        }else {
            user = User.dao.findFirst("select * from `user` where login_account  = ?",loginAccount);
        }
        if(user == null){
            throw new AppException("-1","不存在该账号");
        }else if(user.getStatus().equals("0")){
            throw new AppException("-2","该用户已禁用");
        }else {
            UserPwd userPwd = UserPwd.dao.findFirst("select * from user_pwd where user_id = ? and status = 1 " +
                    "Order by create_time desc",user.getId());
            if(userPwd == null){
                throw new AppException("-3","系统错误，丢失密码，请联系管理员");
            }else if(userPwd.getPwd().equals(pwd)){
                return user;
            }if(!userPwd.getPwd().equals(pwd)){
                throw new AppException("-4","密码错误");
            }else {
                throw new AppException("-5","系统错误");
            }
        }
    }

    public User signUp(String phone, String smsCode, String pwdMd5, String smsId,String openId,Integer parentId) {
        Date date = new Date();
        List<MessageLogs> list = MessageLogs.dao.find("SELECT * FROM message_logs WHERE sms_message_sid = ?",smsId);
        if(list != null && list.size() != 0){
            MessageLogs log = list.get(0);
            if("-1".equals(log.getSTATUS())){
                throw new AppException("-1","验证码已使用");
            }
            if(!log.getCODE().equals(smsCode)){
                throw new AppException("-2","验证码错误");

            }else if(!log.getPHONE().equals(phone)){
                throw new AppException("-3","电话号码不匹配");

            }else if(new Date().getTime() - Long.valueOf(log.getCreateTime()) > 1000*60*5){
                throw new AppException("-4","验证码超时");

            }else {
                log.setSTATUS("-1").update();
                List<User> users = User.dao.find("SELECT * FROM user where phone = ?",phone);
                if(users != null && users.size() != 0){
                    throw new AppException("-5","用户已存在");

                }else {
                    User user = new User();
                    Record record = Db.findFirst("select count(1) user_num from user");
                    String temp = String.valueOf(record.getLong("user_num")+1);
                    String account = generateUserAccount(temp);

                    user.setPhone(phone).setStatus(1).setUpdateTime(date).setCreateTime(date).setLoginAccount(account);
                    if(parentId != null && parentId != 0){
                        dealParent(user,parentId);
                    }
                    if(!StringUtils.isEmpty(openId)){
                        user.setWxOpenId(openId);
                    }
                    user.save();
                    UserPwd pwd = new UserPwd();
                    pwd.setCreateTime(date).setPwd(pwdMd5).setUserId(user.getId()).save();

                    new UserCount().setUserId(user.getId()).setUpdateTime(date).setCreateTime(date)
                            .setOrderPriceNum(0).setReturnPriceNum(0).setSalePriceNum(0).save();

                    //生成私人消息

                    SystemMessage message = new SystemMessage().setTitle("会员注册").setContent("您于"+ Utils.formatDate(date,"yyyy-MM-dd HH:mm:ss")
                    +"成为【新肌会】的第"+temp+"位会员，会员号是【"+account+"】").setType(2).setStatus(1).setIsDelete(0).setCreateTime(date);
                    message.save();
                    Message2User message2User = new Message2User().setMessageId(message.getId()).setIsDelete("0").setStatus("0").setUserId(user.getId()).setCreateTime(date)
                            .setVersion(date);
                    message2User.save();
//                    会员昵称：水木清华
//                    会员ID：15080342
//                    关注时间：2017-05-11  14:12:51
//                    您于2017-05-11  14:12:51成为【新肌会】的第15080342位会员，会员号是【15080342】
                    return user;
                }
            }
        }else {
            throw new AppException("-2","验证码错误");
        }
    }

    public void findPwd(String phone, String smsCode, String pwdMd5, String smsId) {
        Date date = new Date();
        List<MessageLogs> list = MessageLogs.dao.find("SELECT * FROM message_logs WHERE sms_message_sid = ?",smsId);
        if(list != null && list.size() != 0){
            MessageLogs log = list.get(0);
            if("-1".equals(log.getSTATUS())){
                throw new AppException("-1","验证码已使用");
            }
            if(!log.getCODE().equals(smsCode)){
                throw new AppException("-2","验证码错误");

            }else if(!log.getPHONE().equals(phone)){
                throw new AppException("-3","电话号码不匹配");

            }else if(new Date().getTime() - Long.valueOf(log.getCreateTime()) > 1000*60*5){
                throw new AppException("-4","验证码超时");

            }else {
                log.setSTATUS("-1").update();
                User user = User.dao.findFirst("select * from `user` where phone  = ?",phone);
                if(user == null){
                    throw new AppException("-5","该手机号未注册用户");
                }else {
                    UserPwd pwd = new UserPwd();
                    pwd.setCreateTime(date).setPwd(pwdMd5).setUserId(user.getId()).save();
                }
            }
        }else {
            throw new AppException("-2","验证码错误");
        }
    }

    public Map sendSms(String phone) {
        return connectSmsAPI(phone, RandomStringUtils.random(6, false, true));
    }

    private static Map<String,Object> connectSmsAPI(String mobile, String smsCode){
        CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
        HashMap<String, Object> result = null;
        restAPI.init("app.cloopen.com", "8883");
        restAPI.setAccount(MDA.YTXAccountSid, MDA.YTXAccountToken);
        restAPI.setAppId(MDA.YTXAppId);

        result = restAPI.sendTemplateSMS(mobile,"160262" ,new String[]{smsCode});

        MessageLogs message = new MessageLogs();
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            message = new MessageLogs();
            message.setPHONE(mobile);
            message.setCODE(smsCode);
            message.setCreateTime(new Date().getTime()+"");
            message.setTimeUnit(5);
            message.setSTATUS(result.get("statusCode").toString());
            Map<String, Object> dataMap= (Map<String, Object>) result.get("data");
            message.setSmsMessageSid(((Map<String, Object>)dataMap.get("templateSMS")).get("smsMessageSid").toString());
            message.save();
            return (Map<String, Object>) result.get("data");
        }else{
            //异常返回输出错误码和错误信息
            throw  new AppException(result.get("statusCode").toString(),result.get("statusMsg").toString());
//            result.put("errorInfo","错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
        }
    }

    public   Page<User> qryUserList(Integer cPage, Integer pSize, String status, String phone, String start, String end){
        String condition = "";
        List<String> param = new ArrayList<String>();
        if(status != null && !"".equals(status)){
            condition += "and status = ? ";
            param.add(status);

        }
        if(start != null && !"".equals(start)){
            condition += "and create_time > ? ";
            param.add(start);
        }
        if(end != null && !"".equals(end)){
            condition += "and create_time < ? ";
            param.add(end);
        }
        if(phone != null && !"".equals(phone)){
            condition += "and phone like ? ";
            param.add("%"+phone+"%");
        }
        Page<User> users = dao.paginate(cPage,pSize,"SELECT *\n"
                        ,"FROM user u\n" +
                        "WHERE 1=1 "+condition+" order by u.id desc"
                ,param.toArray());
        if(users.getList().size()>0){
            for(int i =0;i< users.getList().size();i++){
                UserCount userCount= UserCount.dao.findById(users.getList().get(i).get("id"));
                if(userCount !=null){
                    double order_price_num =  userCount.getOrderPriceNum()/100;
                    double  return_price_num= userCount.getReturnPriceNum()/100;
                    users.getList().get(i).put("order_price_num",String.valueOf( order_price_num));
                    users.getList().get(i).put("return_price_num",String.valueOf( return_price_num));
                }
            }
        }

        return users;
    }

    public  void updateStatus(int id){
        User user = User.dao.findById(id);
        Integer status= 1;
        user.setStatus(status.equals(user.getStatus()) ? 0 :1).update();
    }

    public UserCount getUserCount(Integer userId) {
        return UserCount.dao.findById(userId);
    }

    public Protocol getUserProtocol() {
        return Protocol.dao.findFirst("SELECT * FROM protocol ORDER BY create_time DESC ");
    }

    public void updateUserInfo(Integer userId, String parentUser, String imgUrl, String nickName) {
        User user = User.dao.findById(userId);
        if(!StringUtils.isEmpty(parentUser)){
            User parent = User.dao.findFirst("SELECT * FROM user WHERE login_account = ?",parentUser);
            if(parent == null){
                throw  new AppException("-1","上级编码不存在");
            }else {
                user.setFirstParentUserId(parent.getId()).setParendUserAccount(parentUser);
                if(parent.getFirstParentUserId() != null){
                    user.setSecondParentUserId(parent.getFirstParentUserId());
                    if(parent.getSecondParentUserId() != null){
                        user.setThirdParentUserId(parent.getSecondParentUserId());
                    }
                }
                user.update();
            }
        }
        if(!StringUtils.isEmpty(imgUrl)){
            user.setHeadImg(imgUrl).update();
        }
        if(!StringUtils.isEmpty(nickName)){
            user.setNickName(nickName).update();
        }
    }

    public void updateUserPhone(Integer userId, String phone, String smsId, String smsCode) {
        Date date = new Date();
        List<MessageLogs> list = MessageLogs.dao.find("SELECT * FROM message_logs WHERE sms_message_sid = ?",smsId);
        if(list != null && list.size() != 0){
            MessageLogs log = list.get(0);
            if("-1".equals(log.getSTATUS())){
                throw new AppException("-1","验证码已使用");
            }
            if(!log.getCODE().equals(smsCode)){
                throw new AppException("-2","验证码错误");

            }else if(!log.getPHONE().equals(phone)){
                throw new AppException("-3","电话号码不匹配");

            }else if(new Date().getTime() - Long.valueOf(log.getCreateTime()) > 1000*60*20){
                throw new AppException("-4","验证码超时");

            }else {
                log.setSTATUS("-1").update();
                User user = User.dao.findById(userId);
                user.setPhone(phone).update();
            }
        }else {
            throw new AppException("-2","验证码错误");
        }
    }

    public Map qryUserAwards(Integer userId) {

        //0未确认1已确认2已提现3已申请-1无效
        Map result = new HashMap();
        User user = User.dao.findById(userId);
        //返回用户头像
        result.put("head_img",user.getHeadImg());

        JoinFee joinFee = JoinFee.dao.findFirst("SELECT * FROM join_fee WHERE user_id = ?",userId);
        if(joinFee != null && joinFee.getStatus().equals(1)){
            result.put("isAgent",1);
        }else {
            result.put("isAgent",0);
        }

        Record total = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status != -1 and user_id = ?",userId);

        Record notConfirm = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status = 0 and user_id = ?",userId);

        Record hasConfirm = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (1,2,3) and user_id = ?",userId);

        result.put("total",total.getBigDecimal("fee").longValue());

        result.put("notConfirm",notConfirm.getBigDecimal("fee").longValue());

        result.put("hasConfirm",hasConfirm.getBigDecimal("fee").longValue());

        Record hasCheckOut = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (2) and user_id = ?",userId);

        Record checkOuting = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (3) and user_id = ?",userId);

        result.put("hasCheckOut",hasCheckOut.getBigDecimal("fee").longValue());

        result.put("checkOuting",checkOuting.getBigDecimal("fee").longValue());

        result.put("canCheckOut",hasConfirm.getBigDecimal("fee").longValue()-hasCheckOut.getBigDecimal("fee").longValue()-checkOuting.getBigDecimal("fee").longValue());

        Record ticheng = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status != -1 and type = 1 and user_id = ?",userId);

        Record ticheng_status1  = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (1) and type = 1 and user_id = ?",userId);

        Record ticheng_status0  = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (0) and type = 1 and user_id = ?",userId);

        result.put("ticheng",ticheng.getBigDecimal("fee").longValue());

        result.put("ticheng_status1",ticheng_status1.getBigDecimal("fee").longValue());

        result.put("ticheng_status0",ticheng_status0.getBigDecimal("fee").longValue());

        Record jintie = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status != -1 and type = 2 and user_id = ?",userId);

        Record jintie_status1  = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (1) and type = 2 and user_id = ?",userId);

        Record jintie_status0  = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (0) and type = 2 and user_id = ?",userId);

        result.put("jintie",jintie.getBigDecimal("fee").longValue());

        result.put("jintie_status1",jintie_status1.getBigDecimal("fee").longValue());

        result.put("jintie_status0",jintie_status0.getBigDecimal("fee").longValue());

        Record tuiguang = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status != -1 and type = 3 and user_id = ?",userId);

        Record tuiguang_status1  = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (1) and type = 3 and user_id = ?",userId);

        Record tuiguang_status0  = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (0) and type = 3 and user_id = ?",userId);

        result.put("tuiguang",tuiguang.getBigDecimal("fee").longValue());

        result.put("tuiguang_status1",tuiguang_status1.getBigDecimal("fee").longValue());

        result.put("tuiguang_status0",tuiguang_status0.getBigDecimal("fee").longValue());

        Record area = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status != -1 and type = 4 and user_id = ?",userId);

        Record area_status1  = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (1) and type = 4 and user_id = ?",userId);

        Record area_status0  = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status in (0) and type = 4 and user_id = ?",userId);

        result.put("area",area.getBigDecimal("fee").longValue());

        result.put("area_status1",area_status1.getBigDecimal("fee").longValue());

        result.put("area_status0",area_status0.getBigDecimal("fee").longValue());

        Record hehuoren = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status != -1 and type = 5 and user_id = ?",userId);

        result.put("hehuoren",hehuoren.getBigDecimal("fee").longValue());

        return result;
    }

    public Map ucIndex(Integer userId) {
        Map result = new HashMap();
        User user = User.dao.findById(userId);
        if(user.getFirstParentUserId() != null && user.getFirstParentUserId() != 0){
            User parent = User.dao.findById(user.getFirstParentUserId());
            user.setParendUserAccount(parent.getPhone());
        }
        Record myOrderNum = Db.findFirst("SELECT count(1) order_num FROM order_list ol,user u WHERE ol.user_id = u.id AND u.id = ? AND ol.status in (0,1,2,3,4,5,6,7)",userId);
        Record tichengNum = Db.findFirst("SELECT count(1) order_num FROM order_list ol,user u WHERE ol.user_id = u.id AND u.first_parent_user_id = ? AND ol.status in (0,1,2,3,4,5,6,7)",userId);
        Record jintieNum = Db.findFirst("SELECT count(1) order_num\n" +
                "FROM order_list ol, user u\n" +
                "WHERE ol.user_id = u.id AND ( u.second_parent_user_id = ? OR u.third_parent_user_id = ? ) AND ol.status in (0,1,2,3,4,5,6,7)",userId,userId);
        result.put("user",user);
        result.put("myOrderNum",myOrderNum.getLong("order_num"));
        result.put("tichengNum",tichengNum.getLong("order_num"));
        result.put("jintieNum",jintieNum.getLong("order_num"));

        Record total = Db.findFirst("SELECT ifnull(sum(fee),0) fee FROM tg_award WHERE status != -1 and user_id = ?",userId);
        result.put("totalTgFee",total.getBigDecimal("fee").longValue());
        Record yyeRecord = Db.findFirst("SELECT sum(fee) fee FROM (\n" +
                "SELECT ifnull(sum(ol.total_fee),0) fee\n" +
                "FROM order_list ol, user u\n" +
                "WHERE ol.user_id = u.id\n" +
                "      AND u.id = ? AND ol.status = 5\n" +
                "UNION\n" +
                "SELECT ifnull(sum(ol.total_fee),0) fee\n" +
                "FROM order_list ol, user u\n" +
                "WHERE ol.user_id = u.id\n" +
                "      AND u.first_parent_user_id = ? AND ol.status = 5) fee_table",userId,userId);
        result.put("yye",yyeRecord.getBigDecimal("fee").longValue());

        JoinFee joinFee = JoinFee.dao.findFirst("SELECT * FROM join_fee WHERE user_id = ?",userId);
        if(joinFee != null && joinFee.getStatus().equals(1)){
            result.put("isAgent",1);
        }else {
            result.put("isAgent",0);
        }
        return result;
    }

    public Map discount(Integer userId) {
        Map result = new HashMap();
        User user = User.dao.findById(userId);
        if(user.getDiscountFlag() == 1){
            result.put("discount",1);
            result.put("count_number",0.8);
        }else {
            result.put("discount",0);
            result.put("count_number",1);
        }

        return result;
    }

    public User loginByWx(String code) {
        WebAccessToken webAccessToken = WxGzhUtils.getAccessToken(code);
//        UserInfo userInfo = WxGzhUtils.userInfo(webAccessToken.getAccessToken(),webAccessToken.getOpenid());
//        System.out.println(userInfo.getErrcode());
        if(webAccessToken != null){
            User user = User.dao.findFirst("select * from user where status = 1 and wx_open_id = ?", webAccessToken.getOpenid());
            if(user == null){
                throw new AppException("-1", webAccessToken.getOpenid());
            }else {
                return user;
            }
        }else {
            throw new AppException("-2",".....");

        }
//        if(StringUtils.isEmpty(userInfo.getErrcode())){
//            User user = User.dao.findFirst("select * from user where status = 1 and wx_open_id = ?",userInfo.getOpenid());
//            if(user == null){
//                throw new AppException("-1",userInfo.getOpenid());
//            }else {
//                return user;
//            }
//        }else {
//            throw new AppException("-2",userInfo.getErrcode());
//        }
    }

    private String generateUserAccount(String temp){
        Integer length = temp.length();
        for(int i = 10;i>length;i--){
            temp = "0"+temp;
        }
        return temp;
    }

    private void dealParent(User user,Integer parentId){
        User first = User.dao.findById(parentId);
        if(first != null){
            user.setFirstParentUserId(parentId);
            if(first.getFirstParentUserId() != null && first.getFirstParentUserId() != 0){
                User second = User.dao.findById(first.getFirstParentUserId());
                if(second != null){
                    user.setSecondParentUserId(second.getId());
                }
                if(second.getFirstParentUserId() != null && second.getFirstParentUserId() != 0){
                    User third = User.dao.findById(second.getFirstParentUserId());
                    if(third != null){
                        user.setThirdParentUserId(third.getId());
                    }
                }
            }
        }
    }
//    public static void main(String[] args){
//        UserServiceImpl userService = new UserServiceImpl();
////        System.out.println(userService.generateUserAccount());
//    }

}
